﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;

namespace Mahanet.Abyss.PathCalculation
{
	public class SingleDataGenerator : IDataGenerator<double, double>
	{
		#region Events

		public event DataGenerationEvent<double, double> DataGenerated;

		#endregion

		#region Fields

		private static Random m_Random = new Random();
	
		#endregion

		#region C'tor

		public SingleDataGenerator()
		{
			LastDataSeriesId = 0;
		}

		#endregion

		#region Public Properties

		public int LastDataSeriesId { get; private set; }
		public FunctionApproximation<double, double> GeneratedFunction { get; private set; }

		#endregion

		#region Public Methods

		public void GenerateFunction()
		{
			LastDataSeriesId++;

			double a = 10.0 * (m_Random.NextDouble() - 0.5);
			double b = 20.0 * (m_Random.NextDouble() - 0.5);
			double c = 200.0 + 100.0 * (m_Random.NextDouble());

			GeneratedFunction = (x) => { x /= 50; return a * x * x + b * x + c; };
		}

		public void GenerateDataPoints(IEnumerable<double> sourcePoints, double maxErrorPercentage)
		{
			foreach (double point in sourcePoints)
			{
				double value = GeneratedFunction(point);

				value *= 1 + (m_Random.NextDouble() - 0.5) * maxErrorPercentage;

				RaiseDataGeneratedEvent(new DataPoint<double, double>(point, value));
			}
		}

		#endregion

		#region Private Methods

		private void RaiseDataGeneratedEvent(DataPoint<double, double> dataPoint)
		{
			if (this.DataGenerated != null)
			{
				this.DataGenerated(dataPoint, LastDataSeriesId);
			}
		}

		#endregion
	}
}
